package net.easyjava.framework.utils;

import net.easyjava.tools.http.HttpTools;
import net.easyjava.tools.lang.MapTools;
import net.easyjava.tools.lang.StringTools;
import net.easyjava.tools.security.SignTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by wxnacy on 16/8/22.
 */
public class SignUtils {
    protected static final String API_SIGN_KEY = "a2dc8a390e92ab87678a5bf922fbd5dd";
    static Logger logger = LoggerFactory.getLogger(SignUtils.class);

    /**
     * 获取加密地址
     * @param url
     * @param params
     * @return
     */
    public static final String getSignUrl(String url,SortedMap<String, String> params){
        params.put("randomStr", StringTools.getRandom(32));
        params.put("timestamp", System.currentTimeMillis()+"");
        String sign = null;
        try {
            sign = SignTools.createSign(params, API_SIGN_KEY);
        } catch (NoSuchAlgorithmException e) {
            logger.error("生成sign失败",e.fillInStackTrace());
        }

        params.put("sign",sign);
        String parStr = MapTools.toParamString(params);

        StringBuffer sb = new StringBuffer();
        sb.append(url).append("?").append(parStr);
        return sb.toString();
    }


    public static void main(String[] args) {
        SortedMap<String, String> params = new TreeMap();
        params.put("id","1");

        String result = getSignUrl("http://user.newoinfo.com/m/user/one",params);
        System.out.println("result = " + result);
        try {
            String data = HttpTools.get(result);
            System.out.println("data = " + data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
